#!/bin/python2

from eztv import parser
from eztv.utils import readPageContent
from eztv.exceptions import PathNotFound
import urwid
import transmissionrpc
import urllib
from subprocess import call
from transmissionrpc import TransmissionError

PALETTE = [
		('selected','white','light magenta'),
		('date', 'white', 'dark red'),
		('bg','black','white')
		]
TRANSMISSIONRPC='192.168.1.19'
TRANSMISSIONPASS=None
COMMANDSTRING=['omxplayer','-ro','hdmi']

class Screen(urwid.WidgetPlaceholder):
	def __init__(self,placeholder):
		self.screens=[]
	def update(self,box):
		self.screens.append(box)
		self.original_widget = box
	def back(self,button):
		if len(self.screens) > 1:
			self.screens.pop()
			self.original_widget=self.screens[-1]
		else:
			top.menu()
	def selectable(self):
		return True
	def keypress(self, size, key):
		if key == 'esc':
			self.back(None)
		else:
			return super(Screen, self).keypress(size,key)

class queryEdit(urwid.Edit):
	signals = urwid.Edit.signals + ['prompt_enter']
	def keypress(self,size,key):
		if key == 'enter':
			urwid.emit_signal(self,'queryEnter',self.edit_text)
		else:
			return urwid.Edit.keypress(self,size,key)
urwid.register_signal(queryEdit,'queryEnter')

def make_button(name, callback,data=None):
	button = urwid.Button(name)
	urwid.connect_signal(button,'click', callback, data)
	return urwid.AttrMap(button,None,focus_map='selected')

class downloadScreen(Screen):
	def __init__(self):
		super(downloadScreen,self).__init__(urwid.SolidFill('/'))
		self.tc = transmissionrpc.Client(TRANSMISSIONRPC)
		self.start()
	
	def start(self):
		torrents = self.tc.get_torrents()
		body=[urwid.Text("Downloads"), urwid.Divider()]
		for i in range(len(torrents)):
			body.append(make_button("%s \n %s"%(torrents[i].name,torrents[i].eta),self.clicked,torrents[i]))
		self.update(urwid.Filler(urwid.Pile(body),'top'))
	def clicked(self,button,torrent):
		body = [urwid.Text(torrent.name), urwid.Divider()]
		body.append(make_button("open",self.openTorrent,torrent))
		body.append(make_button("delete", self.closeTorrent, torrent))
		body.append(make_button("back",self.back))
		self.update(urwid.Filler(urwid.Pile(body),'top'))
	def openTorrent(self, button,torrent):
		call(COMMANDSTRING+[ torrent.downloadDir+'/'+torrent.name])
	def closeTorrent(self,button,torrent):
		self.tc.remove_torrent(torrent.id)
		self.back(None)

class ezSearch(Screen):
	def __init__(self):
		super(ezSearch,self).__init__(urwid.SolidFill('/'))
		self.menu()
		self.resultsFrame = None
	def menu(self):
		body = [urwid.Text("EZ-TV Search"),urwid.Divider(' ')]
		body.append(make_button("Browse the Frontpage", self.browse))
		body.append(make_button("Search for a show", self.get_query))
		self.update(urwid.Filler(urwid.Pile(body)))

	def getResults(self,search=None,number=None):
		page=parser.Page(parser.getFrontPageXPath())
		try:
			if search:
				pageContent=urllib.urlretrieve("http://eztv.it/",filename='/tmp/ts.dat',data="SearchString1=%s&SearchString=&search=Search"%search.replace(" ","+"))
			elif number >= 2:
				pageContent=urllib.urlretrieve("http://eztv.it/",filename='/tmp/ts.dat',data="page_%s"%number)
			else:
				pageContent=urllib.urlretrieve("http://eztv.it/",filename='/tmp/ts.dat')
			page.feed(open(pageContent[0]).read())
			page.process()
		except (PathNotFound, ValueError) as error:
			print (error)
		else:
			return page.matches

	def search(self,text):
		body = urwid.SimpleFocusListWalker([urwid.Text("Search results for "+text),urwid.Divider(' ')])
		query = text.replace(" ", "+")
		results = self.getResults(text)
		self.update(urwid.ListBox(body+self.organize_results(results)))

	def get_query(self,button):
		get_query = queryEdit("Query:") 
		body=[get_query]
		urwid.connect_signal(get_query,"queryEnter",self.search)
		self.update(urwid.Filler(urwid.Pile(body)))
	def organize_results(self,results):
		body = []
		curdate = None
		for res in results:
			if not curdate == res.date:
				curdate = res.date
				body.append(urwid.Text(('date',"Date: %s"%curdate)))
			body.append(make_button(res.releaseName,self.ButtonHandler,res))
		return body

	def browse(self,button,page=1):
		results = self.getResults()
		body = [urwid.Text("Eztv Page# %d"%page),urwid.Divider()]
		body = body + self.organize_results(results)
		body.append(make_button('next', self.browse,page+1))
		if page > 1:
			body.append(make_button('prev',self.browse,page-1))
		self.update(urwid.ListBox(body))
	
	def ButtonHandler(self, button, rel):
		body = [urwid.Text("Do you want to download "+ rel.releaseName),urwid.Divider()]
		body.append(make_button("Yes", self.add_download, rel.downloads[0]))
		body.append(make_button("No", self.back))
		self.update(urwid.Filler(urwid.Pile(body)))
	def add_download(self, button, magnet_link):
		tc = transmissionrpc.Client(TRANSMISSIONRPC,password=TRANSMISSIONPASS)
		tc.add_torrent(magnet_link)

class TopWidget(urwid.WidgetPlaceholder):
	def __init__(self):
		self.windows=[]
		super(TopWidget,self).__init__(urwid.SolidFill('/'))
		self.menu()
		
	def open_box(self,box):
		self.windows.append(box)
		self.original_widget=box
	def close_box(self):
		self.windows.remove(self.windows[-1])
		self.original_widget=self.windows[-1]
	def menu(self):
		body = [urwid.Text("Front Page"), urwid.Divider()]
		for option in "eztv","downloads":
			body.append(make_button(option, self.item_chosen,option))
		self.open_box(urwid.Filler(urwid.Pile(body)))
	def item_chosen(self,button, choice):
		if choice == 'eztv': top.open_box(ezSearch())
		if choice == 'downloads': top.open_box(downloadScreen())
	
def exit_on_q(key):
		if key in ('q','Q'):
			raise urwid.ExitMainLoop()
		if key in ('esc'):
			top.close_box()

top = TopWidget()
urwid.MainLoop(top, PALETTE,unhandled_input=exit_on_q).run()
